package com.hengtiansoft.lfy.activity;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.duowan.mobile.netroid.Request;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.adapter.CollectAdapter;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.been.CollectList;
import com.hengtiansoft.lfy.db.CL_InviteMessgeDao;
import com.hengtiansoft.lfy.db.been.InterpretRecordDB;
import com.hengtiansoft.lfy.entity.CollectListEntity;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.widget.MyToast;
import com.hengtiansoft.pulltorefresh.PullToRefreshBase;
import com.hengtiansoft.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.hengtiansoft.pulltorefresh.PullToRefreshListView;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class CollectionActivity extends BaseActivity {
    private static String TAG = "CollectionActivity";
    private CollectAdapter mCollectAdapter;
    private ArrayList<HashMap<String, Object>> mList = new ArrayList<HashMap<String, Object>>();
    private Context mContext;
    private ProgressDialog pd;
    private int mPostion = -1;
    private ListView mLvCollection;
    private PullToRefreshListView mPullListView;
    private boolean hasMoreData = true;
    private boolean hasData = true;
    private boolean isPullDownRefreshing;
    private boolean isPullUpRefreshing;
    private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
    private ImageView mIvDelete;
    private RuntimeExceptionDao<InterpretRecordDB, Integer> mInterpretRecordDao = null;
    private List<InterpretRecordDB> mInterpretRecordDBList;
    private CL_InviteMessgeDao cl_inviteMessgeDao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_collection);
        initView();
    }

    private void initView() {
        cl_inviteMessgeDao=new CL_InviteMessgeDao(this.getBaseContext());
        pd = new ProgressDialog(mContext, ProgressDialog.THEME_HOLO_LIGHT);
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(true);
        pd.setMessage(getString(R.string.get_data));
        pd.show();
        mPullListView = (PullToRefreshListView) findViewById(
                R.id.lv_collection);
        // 上拉，下拉
        mPullListView.setPullLoadEnabled(true);
        mPullListView.setScrollLoadEnabled(false);
        mLvCollection = mPullListView.getRefreshableView();
        mLvCollection.setDivider(null);
        collectRequest(0);

        mCollectAdapter = new CollectAdapter(mContext, mList);
        mLvCollection.setAdapter(mCollectAdapter);
        mIvDelete = (ImageView) findViewById(R.id.iv_delete);
        mIvDelete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(mContext).setTitle(getString(R.string.prompt))
                        .setMessage(getString(R.string.delete_title)).setPositiveButton(getString(R.string.ok),
                                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        clearCollectRequest();
                    }
                }).setNegativeButton(getString(R.string.cancel), null).show();

            }
        });
        mPullListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                if (!CommonUtils.isNetWorkConnected(mContext)) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                    mPullListView.onPullDownRefreshComplete();
                    return;
                }
                isPullDownRefreshing = true;
                collectRequest(0);
                setLastUpdateTime();
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                if (!CommonUtils.isNetWorkConnected(mContext)) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                    mPullListView.onPullUpRefreshComplete();
                    return;
                }

                isPullUpRefreshing = true;
                collectRequest(mList.size());
            }
        });
        setLastUpdateTime();
        mCollectAdapter.setAdapterListener(new CollectAdapter.CollectAdapterListener() {

            @Override
            public void onTranspondClick(int position) {

            }

            @Override
            public void onOtherClick(int position) {
            }

            @Override
            public void onNotCollectClick(int position) {
            }

//            @Override
//            public void onItemLongClick(int position) {
//                mCollectAdapter.changeImageVisable(position);
//                mCollectAdapter.notifyDataSetChanged();
//                if (position == mCollectAdapter.getCount() - 1) {
//                    mLvCollection.setSelection(ListView.FOCUS_DOWN);
//                }
//            }

            @Override
            public void onItemClick(int position,View view) {
                if("down".equals(view.getTag())){
                    mCollectAdapter.changeImageVisable(-1);
                    mCollectAdapter.notifyDataSetChanged();
                    view.setTag("right");
                }else {
                    mCollectAdapter.changeImageVisable(position);
                    mCollectAdapter.notifyDataSetChanged();
                    if (position == mCollectAdapter.getCount() - 1) {
                        mLvCollection.setSelection(ListView.FOCUS_DOWN);
                    }
                    view.setTag("down");
                }
            }
            @Override
            public void onFullScreenClick(int position) {
                startActivity(new Intent(mContext, FullScrenActivity.class)
                        .putExtra("translate", mCollectAdapter.getItem(position)
                                .get("translation").toString()));
            }

            @Override
            public void onDeleteClick(int position) {
                // 删除操作
                pd.setMessage(getString(R.string.deleting));
                pd.show();
                deletecollectRequest(Config.getUserToken(), position,
                        mCollectAdapter.getItem(position).get("text").toString(),
                        Config.getUserName(),(int) mCollectAdapter.getItem(position).get("serverId"));
            }

            @Override
            public void onCopyClick(int position) {
                // 得到剪贴板管理器
               /* ClipboardManager cmb = (ClipboardManager) getSystemService(
                        Context.CLIPBOARD_SERVICE);
                cmb.setText(
                        mCollectAdapter.getItem(position).get("text").toString()
                                + "\n" + mCollectAdapter.getItem(position)
                                        .get("translation").toString());
                Toast.makeText(mContext, "已复制", Toast.LENGTH_LONG).show();*/
                Intent intent=new Intent(CollectionActivity.this,com.hengtiansoft.lfy.widget.AlertDialog.class);
                intent.putExtra("title",getString(R.string.copy_data));
                intent.putExtra("showTitle",getString(R.string.copy_showtitle));
                intent.putExtra("isCopy",true);
                intent.putExtra("msg",mCollectAdapter.getItem(position)
                        .get("text").toString() + "\n"
                        + mCollectAdapter.getItem(position)
                        .get("translation").toString());
                startActivity(intent);
            }

            @Override
            public void onCollectClick(int position) {
            }
        });
    }

    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        mPullListView.setLastUpdatedLabel(text);
    }

    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }
        return mDateFormat.format(new Date(time));
    }
    private void collectRequest(int start){
        NetHelper.collectList(self, Config.getUserName(), start, 10, Config.getUserToken(), new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                int code = 1;
                String message = null;
                CollectListEntity info= (CollectListEntity) rspData;
                List<CollectList> data = null;
                message = info.getMessage();
                code = info.getRetcode();
                data = info.getData();
                if (code == 0) {
                    if (!data.equals(null)) {
                        if (isPullDownRefreshing) {
                            mList.clear();
                            hasMoreData = true;
                            hasData = true;
                        }
                        for (int i = 0; i < data.size(); i++) {
                            CollectList collectList = data.get(i);
                            HashMap<String, Object> map = new HashMap<String, Object>();
                            map.put("serverId", collectList.getId());
                            map.put("text",
                                    collectList.getSrc_content());
                            map.put("translation",
                                    collectList.getDes_content());
                            mList.add(map);
                        }
                        if (data.size() < 10) {
                            hasMoreData = false;
                        }
                        if (data.size() == 0 && mList.size() == 0) {
                            hasData = false;
                        }
                    }
                } else {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                }
                mCollectAdapter.notifyDataSetChanged();
                pd.dismiss();
                mPullListView.onPullDownRefreshComplete();
                mPullListView.onPullUpRefreshComplete();
                mPullListView.setHasMoreData(hasMoreData);
                mPullListView.setHasData(hasData);
                isPullDownRefreshing = false;
                isPullUpRefreshing = false;
            }
            @Override
            public void failed(String msg) {
                MyToast.show(self,msg);
                pd.dismiss();
                if (isPullDownRefreshing || isPullUpRefreshing) {
                    mPullListView.onPullDownRefreshComplete();
                    mPullListView.onPullUpRefreshComplete();
                    isPullDownRefreshing = false;
                    isPullUpRefreshing = false;
                }
            }
        },CollectListEntity.class);
    }
    //取消网络收藏
    private void deletecollectRequest(String token, int pos,final String text, final String username, final int serverId) {
        mPostion = pos;
        NetHelper.deletecollectRequest(self, token, String.valueOf(serverId), new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                int code=rspData.getRetcode();
                String message=rspData.getMessage();
                if (code == 0) {
                    mList.remove(mPostion);
                    updateDataForInterpretRecordDB(serverId);
                    cl_inviteMessgeDao.deleteCollect("N",serverId+"");
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                } else {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                }
                mCollectAdapter.notifyDataSetChanged();
                pd.dismiss();
                mPostion = -1;
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(self, msg,
                        Toast.LENGTH_LONG).show();
                pd.dismiss();
                mPostion = -1;
            }
        },ServiceResult.class);
    }



    /**
     * 修改收藏状态
     */
    public void updateDataForInterpretRecordDB( int serverId) {
        mInterpretRecordDao = LFYApplication.getHelper(mContext)
                .getInterpretRecordDao();
        if (null != mInterpretRecordDao) {
            try {
                @SuppressWarnings("rawtypes")
                QueryBuilder builder = mInterpretRecordDao.queryBuilder();
                builder.where().eq("serverId", serverId);
                mInterpretRecordDBList = builder.query();
            } catch (SQLException e) {
                mInterpretRecordDBList = null;
            }
        }
        if (null != mInterpretRecordDBList
                && mInterpretRecordDBList.size() > 0) {
            for (int i = 0; i < mInterpretRecordDBList.size(); i++) {
                InterpretRecordDB interpretRecordDB = new InterpretRecordDB();
                interpretRecordDB.setId(mInterpretRecordDBList.get(i).getId());
                interpretRecordDB.setIscollected("N");
                interpretRecordDB
                        .setText(mInterpretRecordDBList.get(i).getText());
                interpretRecordDB.setTranslation(
                        mInterpretRecordDBList.get(i).getTranslation());
                interpretRecordDB.setUsername(
                        mInterpretRecordDBList.get(i).getUsername());
                interpretRecordDB.setFilename(
                        mInterpretRecordDBList.get(i).getFilename());
                interpretRecordDB.setServerId(-1);
                LFYApplication.getHelper(mContext).getInterpretRecordDao()
                        .update(interpretRecordDB);
            }
        }
    }

    private void clearCollectRequest() {
        NetHelper.deleteAllCollect(self, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                int code = 1;
                String message = null;
                message = rspData.getMessage();
                code = rspData.getRetcode();
                if (code == 0) {
                    mList.clear();
                    clearDataForInterpretRecordDB(
                            Config.getUserName(),
                            -1);
                    cl_inviteMessgeDao.deleteCollect("N","");
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                } else {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                }
                mCollectAdapter.notifyDataSetChanged();
                pd.dismiss();
                mPostion = -1;
            }

            @Override
            public void failed(String msg) {
                MyToast.show(self,msg);
                pd.dismiss();
            }
        },ServiceResult.class);
    }

    /**
     * 修改收藏状态
     */
    public void clearDataForInterpretRecordDB(String username, int serverId) {
        mInterpretRecordDao = LFYApplication.getHelper(mContext)
                .getInterpretRecordDao();
        if (null != mInterpretRecordDao) {
            try {
                @SuppressWarnings("rawtypes")
                QueryBuilder builder = mInterpretRecordDao.queryBuilder();
                //builder.where().eq("username", username);
                mInterpretRecordDBList = builder.query();
            } catch (SQLException e) {
                mInterpretRecordDBList = null;
            }
        }
        if (null != mInterpretRecordDBList
                && mInterpretRecordDBList.size() > 0) {
            for (int i = 0; i < mInterpretRecordDBList.size(); i++) {
                InterpretRecordDB interpretRecordDB = new InterpretRecordDB();
                interpretRecordDB.setId(mInterpretRecordDBList.get(i).getId());
                interpretRecordDB.setIscollected("N");
                interpretRecordDB
                        .setText(mInterpretRecordDBList.get(i).getText());
                interpretRecordDB.setTranslation(
                        mInterpretRecordDBList.get(i).getTranslation());
                interpretRecordDB.setUsername(
                        mInterpretRecordDBList.get(i).getUsername());
                interpretRecordDB.setFilename(
                        mInterpretRecordDBList.get(i).getFilename());
                interpretRecordDB.setServerId(-1);
                LFYApplication.getHelper(mContext).getInterpretRecordDao()
                        .update(interpretRecordDB);
            }
        }
    }

}
